import React, { useRef, useImperativeHandle, useState, useEffect } from 'react';
import { Dropdown, CheckList } from 'antd-mobile';
import { observer } from '@formily/react';
import { InbizIcon } from '@inbiz/utils';
import { statusList, dateList, myapplystatusList } from '../utils';
import type { DropdownRef } from 'antd-mobile/es/components/dropdown';
import { TextWidget, getMessage } from '@inbiz/react';
import { getProcessList } from '../service';
import './index.less';

const FilterTab = observer((props: any) => {
  const ref = useRef<DropdownRef>(null);
  const {
    getListData,
    searchValue,
    choosedTabKey,
    popup,
    userInfo,
    rangeConfig,
    processGroup,
    initCondition,
  } = props;

  const [applyCatogory, setApplyCatogory] = useState<{ id: string; name: string; children?: any[] }[]>([{ id: '', name: getMessage('processCenter.all') }]);
  const [applyList, setApplyList] = useState<{ id: string; name: string }[]>([{ id: '', name: getMessage('processCenter.all') }]);
  const [condition, setCondition] = useState<any>(localStorage.getItem('inbiz-process-center-filterTab') ? JSON.parse(localStorage.getItem('inbiz-process-center-filterTab') || '') : initCondition);

  const searchApplyList = async (key: string) => {
    let type = 'all';
    switch (key) {
      case '2':
        type = 'inbox';
        break;
      case '3':
        type = 'APPLI';
        break;
      case '4':
        type = 'drafts';
        break;
      case '5':
        type = 'cctome';
        break;
      case '6':
        type = 'init';
        break;
      case '7':
        type = 'complete';
        break;
      case '8':
        type = 'archive';
        break;
      default:
        break;
    }
    const params = {
      userId: userInfo?.ID,
      type,
      groupType: 'Group',
      dptKey:
        rangeConfig == 'all' || processGroup?.selectedRows?.length == 0
          ? ''
          : processGroup?.groupGuid ?? '',
    };
    let res = await getProcessList(params);
    if (res && res?.details && res?.details?.GroupData) {
      const arr = res.details.GroupData.map((item: { children: any; }) => item.children).flat();
      setApplyCatogory([
        { id: '', name: getMessage('processCenter.all'), children: [...arr] },
        ...res.details.GroupData,
      ]);
      setApplyList([{ id: '', name: getMessage('processCenter.all') }, ...arr]);
    } else {
      setApplyCatogory([{ id: '', name: getMessage('processCenter.all') }]);
      setApplyList([{ id: '', name: getMessage('processCenter.all') }]);
    }
  };

  useImperativeHandle(
    popup,
    () => ({
      close: () => {
        ref.current?.close();
      },
      condition,
      setCondition,
      searchApplyList: async (choosedTabKey: string) => {
        await searchApplyList(choosedTabKey)
      }
    }),
    [],
  );

  const changeCondition = (c: any) => {
    const fiterTabs = {
      ...condition,
      ...c,
    };
    localStorage.setItem('inbiz-process-center-filterTab', JSON.stringify(fiterTabs));
    localStorage.removeItem('inbiz-process-center-selectItem');
    setCondition(fiterTabs);
    getListData(searchValue, {
      ...condition,
      ...c,
    });
    ref.current?.close();
  };

  return (
    <div className={'condition'} id="condition">
      <Dropdown
        ref={ref}
        arrow={
          <InbizIcon type="icon-zhankai2" style={{ fontSize: 12, color: 'rgb(204,204,204)' }} />
        }
      >
        <Dropdown.Item key="1" title={condition.processCategoryName} forceRender>
          {
            <CheckList
              className={'searchDropdown'}
              onChange={(val) => {
                const pName =
                  val.length > 0
                    ? applyCatogory.find((item) => item.id == val[0])?.name
                    : getMessage('processCenter.processGroup');
                changeCondition({
                  processGroupName: val[0],
                  processName: getMessage('processCenter.process'),
                  processDefId: '',
                  processCategoryName: pName,
                });
                let arr = [];
                if (val.length) {
                  arr =
                    applyCatogory.find((ele: { id: string }) => ele.id == val[0])?.children || [];
                } else {
                  arr = applyCatogory[0].children;
                }
                setApplyList([{ id: '', name: getMessage('processCenter.all') }, ...arr]);
              }}
              value={[condition.processGroupName]}
            >
              {applyCatogory.map((item: { id: string; name: string, count?: number }) => {
                return (
                  <CheckList.Item value={item.id} key={item.id}>
                    <TextWidget>{item.name}</TextWidget>
                    {item.count ? `(${item.count})` : null}
                  </CheckList.Item>
                );
              })}
            </CheckList>
          }
        </Dropdown.Item>
        <Dropdown.Item key="2" title={condition.processName} forceRender>
          {
            <CheckList
              className={'searchDropdown'}
              onChange={(val) => {
                const pName =
                  val.length > 0
                    ? applyList.find((item) => item.id == val[0])?.name
                    : getMessage('processCenter.process');
                changeCondition({
                  processGroupName: condition.processGroupName,
                  processName: pName,
                  processDefId: val[0],
                  processCategoryName: condition.processCategoryName as string,
                });
              }}
              value={[condition.processDefId]}
            >
              {applyList.map((item: { id: string; name: string, count?: number }) => {
                return (
                  <CheckList.Item value={item.id} key={item.id}>
                    <TextWidget>{item.name}</TextWidget>
                    {item.count ? `(${item.count})` : null}
                  </CheckList.Item>
                );
              })}
            </CheckList>
          }
        </Dropdown.Item>
        {choosedTabKey == '2' && (
          <Dropdown.Item key="3" title={condition.statusName} forceRender>
            {
              <CheckList
                className={'searchDropdown'}
                onChange={(val) => {
                  const statusName =
                    val.length > 0
                      ? getMessage(statusList.find((item) => item.id == val[0])?.name)
                      : getMessage('processCenter.status');
                  changeCondition({ ...condition, status: val[0], statusName });
                }}
                value={[condition.status]}
              >
                {statusList.map((item: { id: string; name: string }) => {
                  return (
                    <CheckList.Item value={item.id} key={item.id}>
                      <TextWidget>{item.name}</TextWidget>
                    </CheckList.Item>
                  );
                })}
              </CheckList>
            }
          </Dropdown.Item>
        )}
        {choosedTabKey == '6' && (
          <Dropdown.Item key="3" title={condition.statusName} forceRender>
            {
              <CheckList
                className={'searchDropdown'}
                onChange={(val) => {
                  const statusName =
                    val.length > 0
                      ? getMessage(myapplystatusList.find((item) => item.id == val[0])?.name)
                      : getMessage('processCenter.status');
                  changeCondition({ ...condition, status: val[0], statusName });
                }}
                value={[condition.status]}
              >
                {myapplystatusList.map((item: { id: string; name: string }) => {
                  return (
                    <CheckList.Item value={item.id} key={item.id}>
                      <TextWidget>{item.name}</TextWidget>
                    </CheckList.Item>
                  );
                })}
              </CheckList>
            }
          </Dropdown.Item>
        )}
        <Dropdown.Item key="4" title={condition.dateName} forceRender>
          {
            <CheckList
              className={'searchDropdown'}
              onChange={(val) => {
                const dateName =
                  val.length > 0
                    ? getMessage(dateList.find((item) => item.id == val[0])?.name)
                    : getMessage('processCenter.date');
                changeCondition({ ...condition, date: val[0], dateName });
              }}
              value={[condition.date]}
            >
              {dateList.map((item: { id: string; name: string }) => {
                return (
                  <CheckList.Item value={item.id} key={item.id}>
                    <TextWidget>{item.name}</TextWidget>
                  </CheckList.Item>
                );
              })}
            </CheckList>
          }
        </Dropdown.Item>
      </Dropdown>
    </div>
  );
});

export default FilterTab;
